package com.zb.test;

import org.junit.Test;

import java.sql.*;

public class JdbcTest3 {

    @Test
    public void test() throws SQLException {
        String url = "jdbc:mysql://127.0.0.1:3306/java-web?useUnicode=true&characterEncoding=UTF8&useSSL=true";
        String username = "root";
        String password = "root";

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        //加载驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //创建链接
            connection = DriverManager.getConnection(url, username, password);
            connection.setAutoCommit(false);
            //编写sql
            String sql1 = "update account set money = money - 100 where name = 'A'";
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();

//            System.out.println(1/0);

            String sql2 = "update account set money = money + 100 where name = 'B'";
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();

            connection.commit();
            System.out.println("success!");
        } catch (Exception e) {
            assert connection != null;
            connection.rollback();
            e.printStackTrace();
        } finally {
            assert preparedStatement != null;
            preparedStatement.close();
            connection.close();
        }
    }
}
